package entity_user

import (
	"chat_gin/entity/dto"
	"chat_gin/entity/models"
	"chat_gin/utils"
	"fmt"
	"gorm.io/gorm"
	"time"
)

// AddUserInfo 添加用户
func AddUserInfo(param dto.NewUserInfo) error {
	userModel := models.UserBasic{
		Model:         gorm.Model{},
		Name:          param.Name,
		Password:      param.Pwd,
		Phone:         param.Phone,
		Email:         "",
		Identity:      "",
		ClientIP:      "",
		ClientPort:    "",
		LoginTime:     time.Now(),
		HeartbeatTime: time.Now(),
		LogOutTime:    time.Now(),
		IsLogout:      false,
	}
	err := utils.DB.Create(&userModel).Error
	if err != nil {
		fmt.Println("插入用户信息失败", err)
		return err
	}
	return nil
}

// GetUserList 获取用户列表
func GetUserList(param dto.GetUserListParam) ([]*models.UserBasic, int64, error) {
	var getUser []*models.UserBasic
	var total int64
	UserModel := utils.DB.Model(&getUser).Count(&total)
	// 查询分页信息
	UserModel.Limit(param.PageInfo.PageSize).Offset((param.PageInfo.PageIndex - 1) * param.PageInfo.PageSize)
	err2 := UserModel.Find(&getUser).Error
	if err2 != nil {
		return nil, 0, err2
	}
	fmt.Println(getUser)
	return getUser, total, nil
}

// DelUserInfo 删除用户
func DelUserInfo(param dto.DelUserInfo) error {
	var userInfo models.UserBasic
	err := utils.DB.Model(&userInfo).Where("id = ?", param.Id).Delete(&userInfo).Error
	if err != nil {
		return err
	}
	return nil
}

// ChangeUserInfo 修改用户
func ChangeUserInfo(param dto.ChangeUserInfo) error {
	userModel := models.UserBasic{}
	findUser := utils.DB.Model(userModel).Where("id = ?", param.Id).First(&userModel)
	fmt.Println("查询到用户信息", findUser)
	fmt.Println("查询到用户信息ID=", userModel.ID)
	err := findUser.Error
	if err != nil {
		fmt.Println("用户不存在,修改失败", err)
		return err
	} else {
		userModel = models.UserBasic{
			Model:         gorm.Model{},
			Name:          param.Name,
			Password:      param.Pwd,
			Phone:         param.Phone,
			Email:         "",
			Identity:      "",
			ClientIP:      "",
			ClientPort:    "",
			LoginTime:     time.Now(),
			HeartbeatTime: time.Now(),
			LogOutTime:    time.Now(),
			IsLogout:      false,
		}
		err := findUser.UpdateColumns(userModel).Error
		if err != nil {
			return err
		} else {
			return nil
		}
	}
}
